import numpy as np

class Target:
    def __init__(self, grid_size, initial_position=None):
        self.grid_size = grid_size
        self.speed = 15  # 目标移动速度，比无人机慢
        
        # 初始化位置
        if initial_position is None:
            # 在网格中心区域随机生成位置
            center_x = grid_size // 2
            center_y = grid_size // 2
            self.position = (center_x + np.random.randint(-20, 21), 
                           center_y + np.random.randint(-20, 21))
        else:
            self.position = initial_position
            
        # 确保位置在边界内
        self.position = (max(0, min(self.position[0], grid_size-1)),
                        max(0, min(self.position[1], grid_size-1)))
        
        self.is_surrounded = False
        self.escape_attempts = 0
        
    def move_randomly(self):
        """目标随机移动"""
        x, y = self.position
        
        # 随机选择移动方向
        directions = [(0, self.speed), (0, -self.speed), 
                     (self.speed, 0), (-self.speed, 0), (0, 0)]  # 包括停留
        dx, dy = directions[np.random.randint(0, len(directions))]
        
        new_x = max(0, min(x + dx, self.grid_size - 1))
        new_y = max(0, min(y + dy, self.grid_size - 1))
        
        self.position = (new_x, new_y)
        
    def try_escape(self, uav_positions):
        """目标尝试逃脱合围"""
        x, y = self.position
        
        # 计算远离所有无人机的方向
        escape_direction = np.array([0.0, 0.0])
        for uav_pos in uav_positions:
            direction_away = np.array([x - uav_pos[0], y - uav_pos[1]])
            distance = np.linalg.norm(direction_away)
            if distance > 0:
                escape_direction += direction_away / distance
                
        # 归一化逃脱方向
        if np.linalg.norm(escape_direction) > 0:
            escape_direction = escape_direction / np.linalg.norm(escape_direction)
            
        # 按逃脱方向移动
        new_x = x + escape_direction[0] * self.speed
        new_y = y + escape_direction[1] * self.speed
        
        # 边界检查
        new_x = max(0, min(new_x, self.grid_size - 1))
        new_y = max(0, min(new_y, self.grid_size - 1))
        
        self.position = (new_x, new_y)
        self.escape_attempts += 1
        
    def get_state(self):
        return np.array([self.position[0], self.position[1]])